import * as R from 'ramda';

/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
export interface ResourceCrudTableProps {
  resourceName: string;
  detailColumns?: any[];
  itemColumns: any[];
  actionBtnList?: any[];
  tableBtnList?: any[];
  formId?: string;
  onFormEvent?: any;
}

/**
 * AmisSchema
 */
export interface AmisSchema {
  type: string,
  [key: string]: any;
}

export interface ApiSchema {
  method: string,
  url: string,
  data: object,
  [key: string]: any;
}


export function makeCommonApi(url: string): ApiSchema {
  return makeBaseApi(url, {
    "&": "$$",
  })
}

export function makeBaseApi(url: string, data: object): ApiSchema {
  return {
    method: "post",
    url,
    data,
  }
}

export function makeListApi(resourceName: string): ApiSchema {
  return {
    method: "post",
    url: `/api/v1/${resourceName}/list`,
    data: {
      page: '${page}',
      size: "${perPage}",
      sort: "${orderBy ? " + "`${orderBy}:${orderDir}`" +" : 'createdAt:desc'}",
      keywords: "${keywords}",
      "&": "$$",
    },
  }
}

export function makeDetailApi(resourceName: string): ApiSchema {
  return {
    method: "post",
    url: `/api/v1/${resourceName}/detail`,
    data: {
      id: "${id}",
    },
  }
}

export function makeInsertApi(resourceName: string): ApiSchema {
  return makeCommonApi(`/api/v1/${resourceName}/insert`);
}

export function makeUpdateApi(resourceName: string): ApiSchema {
  return makeCommonApi(`/api/v1/${resourceName}/update`);
}

export function makeDeleteApi(resourceName: string): ApiSchema {
  return {
    method: "post",
    url: `/api/v1/${resourceName}/delete`,
    data: {
      id: "${ids ? ids : id}",
    },
  }
}


function makeDeleteButton(deleteApi:any): AmisSchema {
  return {
    label: "删除",
    type: "button",
    actionType: "ajax",
    level: "danger",
    confirmText: "确认要删除？",
    api: deleteApi
  }
}

export function createForm({formId, initApi, updateApi, detailColumns, onEvent}: {formId?: string, initApi:any, updateApi:any, detailColumns:any, onEvent?:any}){
  return {
    id: formId,
    type: "form",
    initApi: initApi,
    debug: true,
    api: updateApi,
    body: detailColumns,
    onEvent
  }
}

export function bindEvent({schema, events}: {schema: AmisSchema, events: {event:string, actions:{actionType: string, [key: string]: any}[]}[]}) {
  if (events && events.length > 0) {
    schema.onEvent = R.fromPairs(events.map(({event, actions}) => ([event,actions])));
  }
  return schema;
}

export function bindData({schema, data}: {schema: AmisSchema, data: any}) {
  if (data) {
    schema.data = data;
  }
  return schema;
}

export function makeDrawerButtonBase({btnText, body, extraProps}: {btnText: string, body: any, extraProps?: Record<any, any>}): AmisSchema {
  return {
    label: btnText,
    type: "button",
    actionType: "drawer",
    drawer: {
      title: btnText,
      closeOnEsc: true,
      closeOnOutside: true,
      width: '50%',
      body: body
    },
    ...extraProps,
  }
}

export function makeDrawerButton({btnText, detailApi, updateApi, detailColumns, onFormEvent, formId, extraProps}: {formId?: string,btnText: string, detailApi:any, updateApi:any, detailColumns:any, onFormEvent?: any, extraProps?:Record<any, any>}): AmisSchema {
  return makeDrawerButtonBase({
    btnText,
    body: createForm({formId, initApi: detailApi, updateApi, detailColumns, onEvent: onFormEvent}),
    ...extraProps
  })
}

export function makeEditButton({detailApi, updateApi, detailColumns, onFormEvent, formId}:{formId?:string, detailApi:any, updateApi:any, detailColumns:any, onFormEvent?:any}): AmisSchema {
  return makeDrawerButton({btnText: "修改", detailApi, updateApi, detailColumns, onFormEvent, formId});
}

export function makeCreateButton({insertApi, detailColumns, onFormEvent, formId}: {formId?:string, insertApi:any, detailColumns:any, onFormEvent?: any}): AmisSchema {
  const btn = makeDrawerButton({formId, btnText: "新增", detailApi: null, updateApi: insertApi, detailColumns, onFormEvent});
  return {...btn, level: "primary"}
}

export function createResourceCrudTableBase({listApi, deleteApi, itemColumns, tableBtnList, actionBtnList}: {listApi: ApiSchema, deleteApi: ApiSchema, itemColumns: any, tableBtnList: any[], actionBtnList:any[]}): AmisSchema {
  return {
    "type": "crud",
    "api": listApi,
    "autoGenerateFilter": {
      "columnsNum": 3,
      "showBtnToolbar": false
    },
    "headerToolbar": [
      "bulkActions",
      {
        "type": "reload",
        "align": "right",
        "icon": "iconfont icon-refresh",
        "label": "刷新",
        "tooltip": "",
      },
      {
        "type": "export-csv",
        "label": "全量导出",
        "align": "right",
        "api": listApi
      },
      ...tableBtnList ?? [],
    ],
    "bulkActions": [
      {
        "label": "批量删除",
        "actionType": "ajax",
        "api": deleteApi,
        "confirmText": "确定要批量删除?"
      },
    ],
    "syncLocation": false,
    "columns": [
      {
        "name": "id",
        "width": 50,
        "label": "ID",
      },
      ...itemColumns,
      {
        "type": "operation",
        "label": "操作",
        "buttons": [
          ...actionBtnList ?? [],
          makeDeleteButton(deleteApi)
        ]
      }
    ]
  }
}

export function createResourceCrudTableSimple({resourceName, detailColumns, itemColumns, actionBtnList, tableBtnList, onFormEvent, formId}: ResourceCrudTableProps): AmisSchema {
  const listApi = makeListApi(resourceName);

  const detailApi = makeDetailApi(resourceName);

  const insertApi = makeInsertApi(resourceName);

  const updateApi = makeUpdateApi(resourceName);

  const deleteApi = makeDeleteApi(resourceName);

  return createResourceCrudTableBase({
    listApi, deleteApi, itemColumns,
    tableBtnList: [
      makeCreateButton({insertApi, detailColumns, onFormEvent, formId}),
      ...tableBtnList??[]
    ],
    actionBtnList: [
      ...actionBtnList ?? [],
      makeEditButton({detailApi, updateApi, detailColumns, onFormEvent, formId}),
    ]
  })
}

export function createResourceCrudTable({resourceName, detailColumns, itemColumns, actionBtnList, tableBtnList, onFormEvent, formId}: ResourceCrudTableProps): AmisSchema {
  const listApi = makeListApi(resourceName);

  const detailApi = makeDetailApi(resourceName);

  const insertApi = makeInsertApi(resourceName);

  const updateApi = makeUpdateApi(resourceName);

  const deleteApi = makeDeleteApi(resourceName);

  return createResourceCrudTableBase({
    listApi,deleteApi, itemColumns: [
        ...itemColumns,
      {
        "name": "createdAt",
        "label": "创建时间",
        "sortable": true,
        "type": "date",
        "fromNow": true,
        "valueFormat": "x",
        'searchable': {
          'type': 'input-datetime-range',
          "format": "x",
          'mode': 'horizontal',
        },
      },
      {
        "name": "createdBy",
        "label": "创建人"
      },
    ],
    tableBtnList: [
      makeCreateButton({insertApi, detailColumns, onFormEvent, formId}),
      ...tableBtnList??[]
    ],
    actionBtnList: [
      ...actionBtnList ?? [],
      makeEditButton({detailApi, updateApi, detailColumns, onFormEvent, formId}),
    ]
  })
}


export interface ResourceCrudListProps {
  resourceName: string;
  detailColumns?: any[];
  cardSpec: { title: any, avatarFieldName: any, body: any, actionBtnList?: any[] };
}

/**
 * 创建资源的CRUD列表
 * @param resourceName
 * @param detailColumns
 * @param cardSpec
 */
export function createResourceCrudList({resourceName, detailColumns, cardSpec}: ResourceCrudListProps): AmisSchema {
  return {
    "type": "crud",
    "api": makeListApi(resourceName),
    "syncLocation": false,
    "mode": "cards",
    "defaultParams": {
      "perPage": 6
    },
    "switchPerPage": false,
    "placeholder": "没有店铺信息，请添加店铺",
    "columnsCount": 3,
    "headerToolbar": [
      "bulkActions",
      {
        "type": "reload",
        "align": "right",
        "icon": "iconfont icon-refresh",
        "label": "刷新",
        "tooltip": "",
      },
      makeCreateButton({insertApi: makeInsertApi(resourceName), detailColumns}),
    ],
    "card": {
      "header": {
        "title": cardSpec.title,
        "avatarText": "${" + cardSpec.avatarFieldName + "|substring:0:2|upperCase}",
        "avatarTextBackground": [
          "#FFB900",
          "#D83B01",
          "#B50E0E",
          "#E81123",
          "#B4009E",
          "#5C2D91",
          "#0078D7",
          "#00B4FF",
          "#008272"
        ]
      },
      "bodyClassName": "padder",
      "body": cardSpec.body,
      "actions": [
        ...cardSpec.actionBtnList ?? [],
        makeEditButton({detailApi: makeDetailApi(resourceName), updateApi: makeUpdateApi(resourceName), detailColumns}),
        makeDeleteButton(makeDeleteApi(resourceName))
      ]
    }
  }
}

export interface CustomComponentProps {
  id?: string,
  name: string,
  compFn: (props: { value: any, onChange: any, data: any }) => any,
}

/**
 * 创建自定义组件
 */
export function createCustomComponent({id, name, compFn}: CustomComponentProps) {
  return {
    ...{id},
    "name": name,
    "asFormItem": true,
    "component": compFn
  }
}